import { Modal, Form, Input, message } from 'antd';
import moment from 'moment';
import { useState } from 'react';

import apiConfig from '@/api/config';
import ContentList from '@/components/ContentList';
import DeleteWrapper from '@/components/DeleteWrapper';
import PageTitle from '@/components/PageTitle';
import QuickCreator from '@/components/QuickCreator';
import TButton from '@/components/TButton';
import ToolBar from '@/components/Toolbar';

import CheckDetail from './components/CheckDetail';
import './index.less';
import { useDatabase } from '@/hooks/useDatabase';

export type CheckT = {
  id: string;
  title: string;
  desc: string;
  records: CheckRecordT[]; // 打卡记录信息
};

export type CheckRecordT = {
  date: string;
  desc: string;
};

const RESTORE_CHECK_LOCAL_KEY = 'todo-check-restore';

const DB_CONFIG = {
  init: true,
  getUrl: apiConfig.getCheck.url,
  restoreKey: RESTORE_CHECK_LOCAL_KEY,
  createUrl: apiConfig.createCheck.url,
  removeUrl: apiConfig.removeCheck.url,
  updateUrl: apiConfig.updateCheck.url,
};

const Check = () => {
  const [show, setShow] = useState(false);

  const {
    data = [],
    activeTarget,
    setActiveTarget,
    create,
    remove,
    update,
  } = useDatabase<CheckT>({
    ...DB_CONFIG,
  });

  const handleCheck = (id: string) => {
    const target = data.find((i) => i.id === id);
    if (target) {
      const record: CheckRecordT = {
        date: moment().toISOString(),
        desc: '',
      };
      target.records.push(record);
      handleUpdate(target);
    }
  };

  const handleCreate = (v: any) => {
    const newCheck = Object.assign({}, v, {
      id: Date.now().toString(),
      records: [],
    }) as CheckT;
    create(newCheck)
      .then(() => {
        message.success('创建成功，请持之以恒！');
      })
      .catch((e) => {
        message.error('创建失败');
      });
  };

  const handleRemove = (item: CheckT) => {
    remove(item)
      .then(() => {
        message.success('移除成功！');
      })
      .catch((e) => {
        console.error('移除失败', e);
      });
  };

  const handleUpdate = (item: CheckT) => {
    update(item)
      .then(() => {
        message.success('已更新');
      })
      .catch((e) => {
        message.error('更新失败');
      })
      .finally(() => {
        setShow(false);
      });
  };

  const handleEdit = () => {
    setShow(true);
  };

  const handleEditDesc = (desc: string, record: CheckRecordT) => {
    if (activeTarget) {
      const targetRecord = activeTarget?.records.find(
        (i) => i.date === record.date,
      );
      if (targetRecord) {
        targetRecord.desc = desc;
      }
      handleUpdate(activeTarget);
    }
  };

  const handleReCheck = (date: string) => {
    if (!activeTarget) {
      return;
    }
    const { records } = activeTarget;
    const insertTarget = moment(date);
    for (let i = 0; i < records.length - 1; i++) {
      const current = moment(records[i].date);
      const next = moment(records[i + 1].date);
      if (
        current.isBefore(insertTarget, 'day') &&
        next.isAfter(insertTarget, 'day')
      ) {
        records.splice(i + 1, 0, {
          date,
          desc: '',
        });
      }
    }
    if (records.length) {
      const firstDay = moment(records[0].date);

      if (insertTarget.isBefore(firstDay)) {
        records.splice(0, 0, {
          date,
          desc: '',
        });
      }
      const lastDay = moment(records[records.length - 1].date);
      if (insertTarget.isAfter(lastDay)) {
        records.push({
          date,
          desc: '',
        });
      }
    }
    handleUpdate(activeTarget);
  };

  const handleCancel = (record: CheckRecordT) => {
    if (!activeTarget) {
      return;
    }
    const targetRecord = activeTarget.records.find(
      (i) => i.date === record.date,
    );
    if (targetRecord) {
      const index = activeTarget.records.indexOf(targetRecord);
      activeTarget.records.splice(index, 1);
    }
    handleUpdate(activeTarget);
  };

  const isCheck = (item: CheckT) => {
    const { records } = item;
    if (!records.length) {
      return false;
    }
    const currentMoment = moment();
    const latestCheck = moment(records[records.length - 1].date);
    return currentMoment.isSame(latestCheck, 'day');
  };

  const renderDetail = () => {
    if (!activeTarget) {
      return <></>;
    }
    return (
      <>
        <PageTitle
          title={activeTarget.title}
          rightTitle={
            <div className="container">
              <TButton
                onClick={() => {
                  handleEdit();
                }}
                plain
                style={{fontSize: '12px', borderRadius: '10px'}}
              >
                编辑
              </TButton>
            </div>
          }
          subTitle={
            <div>
              <span style={{ color: '#999' }}>{activeTarget.desc}</span>
            </div>
          }
        />
        <CheckDetail
          checkItem={activeTarget}
          onEditDesc={handleEditDesc}
          onReCheck={handleReCheck}
          onCancel={handleCancel}
        />
      </>
    );
  };

  const renderForm = () => {
    const config = [
      {
        field: 'title',
        label: '打卡任务名称',
        required: true,
      },
      {
        field: 'desc',
        label: '描述',
      },
      {
        field: 'id',
        label: 'id',
        hidden: true,
      },
    ];

    return (
      <Form
        name="basic"
        initialValues={activeTarget || {}}
        onFinish={handleUpdate}
        autoComplete="off"
        style={{ marginTop: '20px' }}
        layout="vertical"
      >
        {config.map((i) => (
          <Form.Item
            label={i.label}
            name={i.field}
            rules={[{ required: i.required || false }]}
            key={i.field}
            hidden={i.hidden || false}
          >
            <Input autoComplete="off" size="small" />
          </Form.Item>
        ))}
        <Form.Item>
          <TButton submit fullWidth>确定</TButton>
        </Form.Item>
      </Form>
    );
  };

  const renderLeftActions = () => {
    return (
      <QuickCreator
        defaultFields={{
          desc: '打卡项目默认描述',
        }}
        mainField="title"
        onCreate={handleCreate}
        placeholder="回车快速创建打卡任务"
      />
    );
  };

  const renderListItem = (item: CheckT) => {
    return (
      <div className="check-content-list-item">
        <DeleteWrapper
          onRemove={() => {
            handleRemove(item);
          }}
        >
          <div className="check-content-list-item__delete">
            <span></span>
          </div>
        </DeleteWrapper>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span className={`check-content-list-item__title`}>{item.title}</span>

          {isCheck(item) ? (
            <button className="checked-btn">已打卡</button>
          ) : (
            <TButton onClick={() => handleCheck(item.id)}>打卡</TButton>
          )}
        </div>
        <span className="check-content-list-item__desc">{item.desc}</span>
      </div>
    );
  };

  const renderMain = () => {
    if (!activeTarget) {
      return <></>;
    }
    return (
      <ContentList
        list={data}
        activeKey={activeTarget?.id}
        keyField="id"
        onSelect={(key) => {
          const item = data.find((i) => i.id === key) || data?.[0];
          setActiveTarget(item);
        }}
        listRender={renderListItem}
        content={renderDetail()}
      />
    );
  };

  return (
    <>
      <ToolBar leftActions={renderLeftActions()} />

      <div className="check-card__container">
        {renderMain()}
        <Modal
          visible={show}
          onCancel={() => setShow(false)}
          footer={false}
          destroyOnClose
        >
          {renderForm()}
        </Modal>
      </div>
    </>
  );
};

export default Check;
